<script setup lang="ts">
import VChart from 'vue-echarts'
import elementResizeDetectorMaker from 'element-resize-detector'
// import { use } from 'echarts/core';
// import { CanvasRenderer } from 'echarts/renderers';
// import { PieChart, BarChart, LineChart } from 'echarts/charts';
// import {
//   TitleComponent,
//   TooltipComponent,
//   LegendComponent,
// } from 'echarts/components';

// use([
//   CanvasRenderer,
//   PieChart,
//   BarChart,
//   LineChart,
//   TitleComponent,
//   TooltipComponent,
//   LegendComponent,
// ]);
import { debounce, omit } from 'lodash-es'
import { useCurrentElement } from '@vueuse/core'
import type { VChartInstance } from '@/types'
import { CHART_SYMBOL } from '@/symbol'

defineOptions({
  inheritAttrs: false,
})

const props = withDefaults(
  defineProps<{
    autoresize?: boolean
  }>(),
  {
    autoresize: false,
  },
)

const resizeStatus = inject<null | Ref<boolean>>(
  CHART_SYMBOL.RESIZE_STATUS,
)

const el = useCurrentElement()
const erd = elementResizeDetectorMaker()
const chartRef = ref<VChartInstance>()

function resizeHandler() {
  chartRef.value?.resize({
    animation: {
      duration: 1000,
    },
  })
}
function handleAutoresize() {
  onMounted(() => {
    erd.listenTo(el.value, debounce(resizeHandler, 300))
  })
}
const watchStopHandle = watch(
  () => props.autoresize,
  (bol: boolean) => {
    if (!bol)
      return
    handleAutoresize()
  },
  {
    immediate: true,
  },
)
watch(
  () => resizeStatus?.value,
  (bol: boolean | undefined | null) => {
    if (!bol)
      return
    watchStopHandle?.()
    erd.removeAllListeners(el.value)
    resizeHandler()
  },
)

const { theme } = storeToRefs(useDesignStore())
watchEffect(() => {
  if (chartRef.value) {
    chartRef.value.setOption({
      theme: theme.value,
    })
  }
})
</script>

<template>
  <VChart
    ref="chartRef"
    class="v-chart"
    :init-options="{
      locale: 'zh',
    }"
    :theme="theme"
    v-bind="omit($attrs, 'autoresize', 'ref')"
  />
</template>
